package models

import (
	"time"

	"github.com/google/uuid"
	"gorm.io/gorm"
)

type User struct {
	ID                uint      `json:"id" gorm:"primaryKey"`
	UUID              string    `json:"uuid" gorm:"type:varchar(36);uniqueIndex;not null"`
	Username          string    `json:"username" gorm:"type:varchar(50);uniqueIndex;not null"`
	Email             string    `json:"email" gorm:"type:varchar(100);uniqueIndex;not null"`
	Password          string    `json:"-" gorm:"type:varchar(255);not null"`
	FirstName         string    `json:"first_name" gorm:"type:varchar(50)"`
	LastName          string    `json:"last_name" gorm:"type:varchar(50)"`
	Avatar            string    `json:"avatar" gorm:"type:varchar(255)"`
	Phone             string    `json:"phone" gorm:"type:varchar(20)"`
	IsActive          bool      `json:"is_active" gorm:"default:false"`
	IsEmailVerified   bool      `json:"is_email_verified" gorm:"default:false"`
	EmailVerifiedAt   *time.Time `json:"email_verified_at"`
	LastLoginAt       *time.Time `json:"last_login_at"`
	PasswordResetToken string    `json:"-" gorm:"type:varchar(255)"`
	PasswordResetExpiry *time.Time `json:"-"`
	EmailVerificationToken string `json:"-" gorm:"type:varchar(255)"`
	EmailVerificationExpiry *time.Time `json:"-"`
	CreatedAt         time.Time `json:"created_at"`
	UpdatedAt         time.Time `json:"updated_at"`
	DeletedAt         gorm.DeletedAt `json:"-" gorm:"index"`

	// 关联关系
	UserRoles []UserRole `json:"user_roles" gorm:"foreignKey:UserID"`
	Roles     []Role     `json:"roles" gorm:"many2many:user_roles;"`
}

// BeforeCreate 在创建用户前生成UUID
func (u *User) BeforeCreate(tx *gorm.DB) error {
	if u.UUID == "" {
		u.UUID = uuid.New().String()
	}
	return nil
}

// TableName 指定表名
func (User) TableName() string {
	return "users"
}

// HasRole 检查用户是否拥有指定角色
func (u *User) HasRole(roleName string) bool {
	for _, role := range u.Roles {
		if role.Name == roleName {
			return true
		}
	}
	return false
}

// HasPermission 检查用户是否拥有指定权限
func (u *User) HasPermission(permissionName string) bool {
	for _, role := range u.Roles {
		for _, permission := range role.Permissions {
			if permission.Name == permissionName {
				return true
			}
		}
	}
	return false
}